package util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 */
public class Md5Util {

	public static String digest(String str) {
		byte[] bytes;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
			bytes = messageDigest.digest();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

		StringBuilder builder = new StringBuilder();
		for (byte aByte : bytes) {
			if (Integer.toHexString(0xFF & aByte).length() == 1) {
				builder.append("0").append(Integer.toHexString(0xFF & aByte));
			} else {
				builder.append(Integer.toHexString(0xFF & aByte));
			}
		}
		return builder.toString();
	}

}